package com.wstx.mediaserver.util;

import cn.hutool.core.util.RandomUtil;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
统一约定：fileName=hexie.jpg
extName=jpg(没有点！)
mainName=hexie
storeName=hexie-202201281743.jpg
 */

@Accessors(chain = true)
public class FileUtil {
    public static final String IMAGE = "image";
    public static final String TXT = "document";
    public static final String MUSIC = "music";
    public static final String VIDEO = "video";
    public static final String OTHER = "other";

    public static String extName(String fileName) {
        return fileName.substring(fileName.indexOf('.') + 1);
    }

    public static String mainName(String fileName) {
        return fileName.substring(0, (fileName.indexOf('.')));
    }

    //极端情况之装怪：实测Windows系统确实可以有空白文件名的文件（就叫.png），
    //Vue上传组件竟然也可以上传这个文件，这是否
    public static String excludeBlankName(String fileName) throws Exception {
        int dotIndex = fileName.indexOf('.');
        if (dotIndex == -1) {
            throw new Exception("文件名错误：无 '.' 符号");
        }
        String realName = fileName.substring(0, dotIndex);
        return StringUtils.isBlank(realName) ?
                RandomUtil.randomString(8) + "." + extName(fileName): fileName;
    }

    //获取文件类型（写死的字符串）
    //可穿hexie.jpg 或 jpg，这里再做个判断
    public static String fileType(String nameStr) {
        String extName = nameStr.contains(".") ? extName(nameStr) : nameStr;

        String documents = "txt doc pdf ppt pps xlsx xls docx";
        String music = "mp3 wav wma mpa ram ra aac aif m4a";
        String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
        String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
        if (image.contains(extName)) {
            return IMAGE;
        } else if (documents.contains(extName)) {
            return TXT;
        } else if (music.contains(extName)) {
            return MUSIC;
        } else if (video.contains(extName)) {
            return VIDEO;
        } else {
            return OTHER;
        }

    }

    //预设上传的服务器文件名
    //为文件名防重，顺便加个友好时间戳，故约定上传到服务器上的文件名为：
    //yyyyMMddhhmmss-fileName
    //示例：hexie-202201281743.jpg
    public static String storeName(String fileName) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String timestamp = "-" + dateFormat.format(now);
        return mainName(fileName) + timestamp + "." + extName(fileName);
    }

    /*
    获取预存储服务器文件全限路径，E:\test\image\hexie-202201281743.jpg
    location:spring.servlet.multipart.location
     */
    public static String remoteFullPath(String location, String type, String storeName) {
        return location + File.separator + type + File.separator + storeName;
    }

//    将内存中的MultipartFile根据预设的文件全限路径传输到服务器
    public static void transmission(MultipartFile file, String remoteFullPath) throws IOException {
        File prestoreFile = new File(remoteFullPath).getCanonicalFile();
        if (!prestoreFile.getParentFile().exists()){
            if (!prestoreFile.getParentFile().mkdir()){
                System.out.println("父目录不存在且创建失败");
            }
        }
        file.transferTo(prestoreFile);
    }

    public static void main(String[] args) throws Exception {
        excludeBlankName("sb");
    }
}
